package com.yzh.openai.trigger.http;

import com.alibaba.fastjson.JSON;
import com.yzh.openai.domain.auth.service.IAuthService;
import com.yzh.openai.domain.openai.model.aggregates.ChatProcessAggregate;
import com.yzh.openai.domain.openai.model.entity.MessageEntity;
import com.yzh.openai.domain.openai.service.IChatService;
import com.yzh.openai.trigger.http.dto.ChatGLMRequestDTO;
import com.yzh.openai.types.common.Constants;
import com.yzh.openai.types.exception.BusinessException;
import com.yzh.zhipu.model.vo.Model;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

/**
 * 问答服务控制器
 */
@Slf4j
@RestController()
@CrossOrigin("${app.config.cross-origin}")
@RequestMapping("api/${app.config.api-version}")
public class ChatAiServiceController {
    @Resource
    private IChatService chatService;
    @Resource
    private IAuthService authService;

    @PostMapping("chat/completions")
    public ResponseBodyEmitter completionsStream(@RequestBody ChatGLMRequestDTO requestDTO, @RequestHeader("Authorization") String token, HttpServletResponse response) {
        log.info("流式问答请求开始，使用模型：{} 请求信息：{}", requestDTO.getModel(), JSON.toJSONString(requestDTO.getMessages()));
        try {
            // 1. 基础配置；流式输出、编码、禁用缓存
            response.setContentType("text/event-stream");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Cache-Control", "no-cache");
            
            //2.获取openid
            String openid = authService.getOpenid(token);
            //3.构建参数
            ChatProcessAggregate chatProcessAggregate = ChatProcessAggregate.builder()
                    .openid(openid)
                    .model(Model.getEnum(requestDTO.getModel()))  
                    .messages(requestDTO.getMessages().stream()
                            .map(entity -> MessageEntity.builder()
                                    .role(entity.getRole())
                                    .content(entity.getContent())
                                    .name(entity.getName())
                                    .build())
                            .collect(Collectors.toList()))
                    .build();
            
            //4.请求结果&返回
            return chatService.completions(chatProcessAggregate);
        }catch (Exception e) {
            log.error("流式应答异常，请求模型：{}", requestDTO.getModel(), e);
            throw new BusinessException(Constants.ResponseCode.CHAT_ERROR, "流式应答异常");
        }
    }
}
